package com.example.secondhandmall.fragment;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.secondhandmall.R;
import com.example.secondhandmall.activity.ModifyInfoActivity;
import com.example.secondhandmall.api.Api;
import com.example.secondhandmall.api.ApiConfig;
import com.example.secondhandmall.api.MyCallback;
import com.example.secondhandmall.entity.BaseResponse;
import com.example.secondhandmall.entity.LoginResponse;
import com.example.secondhandmall.util.FileUtils;
import com.example.secondhandmall.util.RealPathFromUriUtils;
import com.example.secondhandmall.util.StringUtils;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;

public class PutFragment extends BaseFragment {
    private static final int IMAGE_REQUEST_CODE = 0;
    String tag = "ReadPhotoActivity";

    private EditText etTitle;
    private EditText etDetail;
    private LinearLayout addImg;
    private ImageView ivImg;
    private EditText etAddress;
    private EditText etPrice;
    private Button btnReset;
    private Button btnPut;
    private Boolean img_select=false;
    private String path;
    private Spinner spType;
    private String title;
    private String detail;
    private String address;
    private String price;
    private String type;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    reset();
                    break;
            }
        }
    };

    public PutFragment() {
    }

    public static PutFragment newInstance() {
        PutFragment fragment = new PutFragment();
        return fragment;
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_put;
    }

    @Override
    protected void initView() {
        etTitle = mRootView.findViewById(R.id.et_title);
        etDetail = mRootView.findViewById(R.id.et_detail);
        addImg = mRootView.findViewById(R.id.add_img);
        ivImg = mRootView.findViewById(R.id.iv_img);
        etAddress = mRootView.findViewById(R.id.et_address);
        etPrice = mRootView.findViewById(R.id.et_price);
        btnReset = mRootView.findViewById(R.id.btn_reset);
        btnPut = mRootView.findViewById(R.id.btn_put);
        spType = mRootView.findViewById(R.id.spinner_simple);
    }

    @Override
    protected void initData() {
        addImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addImg();
            }
        });
        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reset();
            }
        });
        btnPut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                title = etTitle.getText().toString().trim();
                detail = etDetail.getText().toString().trim();
//                String img = ivImg.getText().toString().trim();
                address = etAddress.getText().toString().trim();
                price = etPrice.getText().toString().trim();
                type = spType.getSelectedItem().toString();

                if (StringUtils.isEmpty(title)) {
                    showToast(etTitle.getHint().toString());
                    return;
                }
                if (StringUtils.isEmpty(detail)) {
                    showToast(etDetail.getHint().toString());
                    return;
                }
//                if(StringUtils.isEmpty(img)){
//                    showToast(etTitle.getHint().toString());
//                    return;
//                }
                if(!img_select){
                    showToast("请选择图片！");
                    return;
                }
                if (StringUtils.isEmpty(address)) {
                    showToast(etAddress.getHint().toString());
                    return;
                }
                if (StringUtils.isEmpty(price)) {
                    showToast("请输入价格！");
                    return;
                }
                if(type.equals("请选择类型")){
                    showToast("请选择类型！");
                    return;
                }
//                put();
                uploadImage();
            }
        });
    }

    //重置
    private void reset() {
        etTitle.setText("");
        etDetail.setText("");
//                ivImg.setText("");
        ivImg.setImageBitmap(null);
        img_select = false;
        etAddress.setText("");
        etPrice.setText("");
    }

    //通过接口上架物品
    private void put() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("title", etTitle.getText());
        params.put("detail", etDetail.getText());
//        params.put("img",ivImg.getText());
        params.put("address", etAddress.getText());
        params.put("price", etPrice.getText());
        Api.config(ApiConfig.PUT_GOODS, params).getRequest(new MyCallback() {
            @Override
            public void onSuccess(String res) {
//                showToastSync(res);//不会运行到下面
                LoginResponse putResponse = new Gson().fromJson(res, LoginResponse.class);
                if (putResponse.getCode() == 200&&putResponse.isData()) {
//                    reset();
                    mHandler.sendEmptyMessage(0);
                    showToastSync("上架成功！");
                } else {
                    showToastSync("上架失败！");
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync("请求失败！");
            }
        });
    }

    private void addImg() {
        //动态申请权限
        ActivityCompat.requestPermissions(getActivity(),
                new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                1);

        Intent galleryIntent=new Intent(Intent.ACTION_GET_CONTENT);
        galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
        galleryIntent.setType("image/*");//图片
        startActivityForResult(galleryIntent,2);//跳转，传递打开相册请求码

//        Intent intent = new Intent(Intent.ACTION_PICK, null);
//        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//        startActivityForResult(intent, 2);

//        // 激活系统图库，选择一张图片
//        Intent intent = new Intent();
//        intent.setAction(Intent.ACTION_PICK);
//        intent.setType("image/*");
//        startActivityForResult(intent, 0);
    }

    //第二步就是返回的时候获取相册的路径
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2) {
            if (null != data) {
                Uri uri = data.getData();
                Log.i(tag, "onActivityResult" + uri.toString());
//                String imagePath = getRealPathFromURI(uri);
//                Log.e(tag, "真实路径" + imagePath.toString());
                ShowPhoto2(uri);
                img_select = true;
            }
        }
    }

    /*显示图片*/
    private void showPicture (String img_uri){
        ivImg.setImageBitmap(BitmapFactory.decodeFile(img_uri));
//        ivImg.setImageURI(Uri.parse(img_uri));
    }

    private void ShowPhoto1(Uri uri) {
        ivImg.setImageURI(uri);
    }

    private void ShowPhoto2(Uri uri) {
        ContentResolver cr = getActivity().getContentResolver();
        try {
            Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
            //设置图片显示，可以看到效果
            /* 将Bitmap设定到ImageView */
            ivImg.setImageBitmap(bitmap);
//            Log.e("ff","看到");
            Log.e("uri", String.valueOf(uri));
            Log.i(tag, "onActivityResult" + uri.toString());

            path = RealPathFromUriUtils.getRealPathFromUri(getActivity(),uri);
            Log.e(tag, "真实路径：" + path);
            System.out.println(path);
//            File file = new File(path);
//            uploadImage(file);//这里只获取路径不上传

//            String imagePath = getRealPathFromURI(uri);
        } catch (FileNotFoundException e) {
            Log.e("Exception", e.getMessage(),e);
        }
    }

    //将文件的uri转化为文件路径
    private String getRealPathFromURI(Uri contentURI) {
        String result;
        Cursor cursor = getActivity().getContentResolver().query(contentURI, null, null, null, null);
        //不能直接调用contentprovider的接口函数，需要使用contentresolver对象，通过URI间接调用contentprovider
        if (cursor == null) {
            // Source is Dropbox or other similar local file path
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    //上架商品（连上传图片）
    private void uploadImage() {
        File file = new File(path);
        String account = getStringFromSp("account");

        OkHttpClient httpClient = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/octet-stream");//设置类型，类型为八位字节流
        RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体

        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("multipartFiles", file.getName(), requestBody)//文件名
                .addFormDataPart("goodsAddress",address)
                .addFormDataPart("goodsName",title)
                .addFormDataPart("goodsPrice",price)
                .addFormDataPart("goodsSignature",detail)
                .addFormDataPart("goodsType",type)
                .addFormDataPart("userId",account)
                .build();
        Request request = new Request.Builder()
                .url(ApiConfig.BASE_URl+ApiConfig.GOODS_BY_ID)
                .post(multipartBody)
                .build();
        Call call = httpClient.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e);
                showToastSync("请求失败！");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //在这里根据返回内容执行具体的操作
                final String res=response.body().string();
                System.out.println(res);
                LoginResponse putResponse = new Gson().fromJson(res,LoginResponse.class);
                if (response.code()==200&&putResponse.isData()){
                    mHandler.sendEmptyMessage(0);
                    showToastSync("上架成功！");
                }else {
                    showToastSync("上架失败！");
                }
            }
        });
    }
}